const express = require('express');
const simpleGit = require('simple-git');
const fs = require('fs-extra');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

const router = express.Router();

/**
 * 测试API连接
 * GET /api/git/test
 */
router.get('/test', async (req, res) => {
  res.json({
    success: true,
    message: 'Git API 连接正常',
    timestamp: new Date().toISOString()
  });
});

/**
 * 验证Git仓库地址
 * POST /api/git/validate
 */
router.post('/validate', async (req, res) => {
  try {
    const { repoUrl } = req.body;
    
    if (!repoUrl) {
      return res.status(400).json({ error: '仓库地址不能为空' });
    }

    // 基本URL格式验证
    const gitUrlPattern = /^(https?:\/\/|git@).*\.git$|^https?:\/\/github\.com\/.*\/.*$/;
    if (!gitUrlPattern.test(repoUrl)) {
      return res.status(400).json({ error: '仓库地址格式不正确' });
    }

    // 尝试获取仓库信息（不克隆，只检查可访问性）
    const git = simpleGit();
    const tempDir = path.join(__dirname, '../../temp', `validate_${Date.now()}`);
    
    try {
      await fs.ensureDir(tempDir);
      await git.clone(repoUrl, tempDir, ['--depth', '1']);
      
      // 读取package.json获取项目信息
      const packagePath = path.join(tempDir, 'package.json');
      let projectInfo = {
        name: '未知项目',
        version: '1.0.0',
        buildScript: null,
        framework: 'unknown'
      };

      if (await fs.pathExists(packagePath)) {
        const pkg = await fs.readJson(packagePath);
        projectInfo = {
          name: pkg.name || '未知项目',
          version: pkg.version || '1.0.0',
          buildScript: pkg.scripts?.build || null,
          framework: detectFramework(pkg),
          other: pkg
        };
      }

      // 清理临时目录
      await fs.remove(tempDir);

      res.json({
        success: true,
        message: '仓库验证成功',
        projectInfo
      });

    } catch (cloneError) {
      await fs.remove(tempDir);
      throw cloneError;
    }

  } catch (error) {
    console.error('Git验证错误:', error);
    res.status(500).json({ 
      error: '仓库验证失败', 
      message: error.message.includes('not found') ? '仓库不存在或无权限访问' : '网络连接异常'
    });
  }
});

/**
 * 克隆Git仓库
 * POST /api/git/clone
 */
router.post('/clone', async (req, res) => {
  try {
    const { repoUrl, branch = 'main', tag, refType = 'branch' } = req.body;
    
    if (!repoUrl) {
      return res.status(400).json({ error: '仓库地址不能为空' });
    }

    const projectId = uuidv4();
    const cloneDir = path.join(__dirname, '../../temp', projectId);
    
    await fs.ensureDir(cloneDir);
    
    const git = simpleGit();
    
    // 根据引用类型克隆
    if (refType === 'tag' && tag) {
      // 克隆指定标签
      await git.clone(repoUrl, cloneDir, ['--depth', '1', '--branch', tag]);
    } else {
      // 克隆指定分支
      await git.clone(repoUrl, cloneDir, ['--single-branch', '--branch', branch]);
    }
    
    // 获取项目详细信息
    const projectGit = simpleGit(cloneDir);
    const log = await projectGit.log(['-1']); // 获取最新提交
    
    const projectInfo = await analyzeProject(cloneDir);
    
    res.json({
      success: true,
      projectId,
      clonePath: cloneDir,
      refType,
      ref: refType === 'tag' ? tag : branch,
      projectInfo: {
        ...projectInfo,
        lastCommit: {
          hash: log.latest.hash,
          message: log.latest.message,
          author: log.latest.author_name,
          date: log.latest.date
        }
      }
    });

  } catch (error) {
    console.error('Git克隆错误:', error);
    res.status(500).json({ 
      error: '仓库克隆失败', 
      message: error.message 
    });
  }
});

/**
 * 获取仓库分支列表
 * POST /api/git/branches
 */
router.post('/branches', async (req, res) => {
  try {
    const { repoUrl, search = '' } = req.body;
    
    if (!repoUrl) {
      return res.status(400).json({ error: '仓库地址不能为空' });
    }

    const git = simpleGit();
    
    // 获取远程分支信息
    const branches = await git.listRemote(['--heads', repoUrl]);
    let branchList = branches
      .split('\n')
      .filter(line => line.trim())
      .map(line => {
        const parts = line.split('\t');
        const branchName = parts[1].replace('refs/heads/', '');
        return {
          name: branchName,
          hash: parts[0]
        };
      });

    // 模糊搜索功能
    const searchStr = String(search || '');
    if (searchStr.trim()) {
      const searchTerm = searchStr.toLowerCase().trim();
      branchList = branchList.filter(branch => 
        branch.name.toLowerCase().includes(searchTerm)
      );
      
      // 按相关性排序：优先显示以搜索词开头的分支
      branchList.sort((a, b) => {
        const aStartsWith = a.name.toLowerCase().startsWith(searchTerm);
        const bStartsWith = b.name.toLowerCase().startsWith(searchTerm);
        
        if (aStartsWith && !bStartsWith) return -1;
        if (!aStartsWith && bStartsWith) return 1;
        
        // 其次按包含搜索词的位置排序
        const aIndex = a.name.toLowerCase().indexOf(searchTerm);
        const bIndex = b.name.toLowerCase().indexOf(searchTerm);
        
        if (aIndex !== bIndex) return aIndex - bIndex;
        
        // 最后按分支名字母顺序排序
        return a.name.localeCompare(b.name);
      });
    } else {
      // 如果没有搜索词，按常见分支优先级排序
      branchList.sort((a, b) => {
        const priority = ['main', 'master', 'develop', 'dev', 'staging', 'release'];
        const aPriority = priority.indexOf(a.name);
        const bPriority = priority.indexOf(b.name);
        
        // 如果都在优先级列表中，按优先级排序
        if (aPriority !== -1 && bPriority !== -1) {
          return aPriority - bPriority;
        }
        
        // 优先级分支排在前面
        if (aPriority !== -1) return -1;
        if (bPriority !== -1) return 1;
        
        // 其他分支按字母顺序排序
        return a.name.localeCompare(b.name);
      });
    }

    res.json({
      success: true,
      branches: branchList,
      total: branchList.length,
      search: searchStr
    });

  } catch (error) {
    console.error('获取分支错误:', error);
    res.status(500).json({ 
      error: '获取分支失败', 
      message: error.message 
    });
  }
});

/**
 * 获取仓库标签列表
 * POST /api/git/tags
 */
router.post('/tags', async (req, res) => {
  try {
    const { repoUrl, search = '' } = req.body;
    
    if (!repoUrl) {
      return res.status(400).json({ error: '仓库地址不能为空' });
    }

    const git = simpleGit();
    
    // 获取远程标签信息
    const tags = await git.listRemote(['--tags', repoUrl]);
    let tagList = tags
      .split('\n')
      .filter(line => line.trim() && !line.includes('^{}')) // 过滤掉注释标签
      .map(line => {
        const parts = line.split('\t');
        const tagName = parts[1].replace('refs/tags/', '');
        return {
          name: tagName,
          hash: parts[0]
        };
      });

    // 模糊搜索功能
    const searchStr = String(search || '');
    if (searchStr.trim()) {
      const searchTerm = searchStr.toLowerCase().trim();
      tagList = tagList.filter(tag => 
        tag.name.toLowerCase().includes(searchTerm)
      );
      
      // 按相关性排序
      tagList.sort((a, b) => {
        const aStartsWith = a.name.toLowerCase().startsWith(searchTerm);
        const bStartsWith = b.name.toLowerCase().startsWith(searchTerm);
        
        if (aStartsWith && !bStartsWith) return -1;
        if (!aStartsWith && bStartsWith) return 1;
        
        const aIndex = a.name.toLowerCase().indexOf(searchTerm);
        const bIndex = b.name.toLowerCase().indexOf(searchTerm);
        
        if (aIndex !== bIndex) return aIndex - bIndex;
        
        return a.name.localeCompare(b.name);
      });
    } else {
      // 按版本号倒序排列（最新的在前）
      tagList.sort((a, b) => {
        // 尝试按语义化版本排序
        const versionPattern = /^v?(\d+)\.(\d+)\.(\d+)/;
        const aMatch = a.name.match(versionPattern);
        const bMatch = b.name.match(versionPattern);
        
        if (aMatch && bMatch) {
          const aMajor = parseInt(aMatch[1]);
          const bMajor = parseInt(bMatch[1]);
          if (aMajor !== bMajor) return bMajor - aMajor;
          
          const aMinor = parseInt(aMatch[2]);
          const bMinor = parseInt(bMatch[2]);
          if (aMinor !== bMinor) return bMinor - aMinor;
          
          const aPatch = parseInt(aMatch[3]);
          const bPatch = parseInt(bMatch[3]);
          return bPatch - aPatch;
        }
        
        // 如果不是语义化版本，按名称倒序排列
        return b.name.localeCompare(a.name);
      });
    }

    res.json({
      success: true,
      tags: tagList,
      total: tagList.length,
      search: searchStr
    });

  } catch (error) {
    console.error('获取标签错误:', error);
    res.status(500).json({ 
      error: '获取标签失败', 
      message: error.message 
    });
  }
});

/**
 * 分析项目结构和配置
 */
async function analyzeProject(projectPath) {
  const info = {
    name: '未知项目',
    version: '1.0.0',
    framework: 'unknown',
    buildScript: null,
    dependencies: {},
    devDependencies: {},
    buildTool: null
  };

  try {
    // 读取package.json
    const packagePath = path.join(projectPath, 'package.json');
    if (await fs.pathExists(packagePath)) {
      const pkg = await fs.readJson(packagePath);
      info.name = pkg.name || info.name;
      info.version = pkg.version || info.version;
      info.buildScript = pkg.scripts?.build;
      info.dependencies = pkg.dependencies || {};
      info.devDependencies = pkg.devDependencies || {};
      info.framework = detectFramework(pkg);
    }

    // 检测构建工具
    const configFiles = {
      webpack: ['webpack.config.js', 'webpack.config.ts'],
      vite: ['vite.config.js', 'vite.config.ts'],
      rollup: ['rollup.config.js', 'rollup.config.ts'],
      parcel: ['parcel.config.js', '.parcelrc']
    };

    for (const [tool, files] of Object.entries(configFiles)) {
      for (const file of files) {
        if (await fs.pathExists(path.join(projectPath, file))) {
          info.buildTool = tool;
          break;
        }
      }
      if (info.buildTool) break;
    }

  } catch (error) {
    console.error('项目分析错误:', error);
  }

  return info;
}

/**
 * 检测前端框架
 */
function detectFramework(pkg) {
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
  
  if (deps.react || deps['@types/react']) return 'react';
  if (deps.vue || deps['@vue/cli-service']) return 'vue';
  if (deps.angular || deps['@angular/core']) return 'angular';
  if (deps.svelte) return 'svelte';
  if (deps.next) return 'nextjs';
  if (deps.nuxt) return 'nuxtjs';
  
  return 'vanilla';
}

module.exports = router;
